package threads;

import java.util.concurrent.Semaphore;

public class SemaphoreExample {
    private Semaphore semaphore=new Semaphore(5);//定义五个信号量
    public boolean parking()throws InterruptedException
    {
        if (semaphore.tryAcquire())
        {//如果tryAcquire()为true,信号量减一
            System.out.println(Thread.currentThread().getName()+":停车成功");
            return true;
        }
        else
        {
            System.out.println(Thread.currentThread().getName()+":停车不成功");
            return false;
        }


    }
    public void leaving()throws InterruptedException
    {
        semaphore.release();
        System.out.println("开走了一张车，空出一个停车位");
    }
    public static void main(String []args)throws InterruptedException
    {
        int tryToPark=10;//模拟十张车
        final SemaphoreExample semaphoreExample=new SemaphoreExample();
        Thread[] parkers=new Thread[tryToPark];
        for (int i=0;i<tryToPark;i++)
        {
            parkers[i]=new Thread(new Runnable() {
                @Override
                public void run() {
                    try {
                        long random=(long)(Math.random()*1000);
                        Thread.sleep(random);
                        if (semaphoreExample.parking())
                        {
                            long parkingTime=(long)(Math.random()*1200);
                            Thread.sleep(parkingTime);
                            semaphoreExample.leaving();
                        }
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }

                }
            });
            parkers[i].start();//每个线程都开始执行
        }
        for (int i=0;i<tryToPark;i++)
        {
            parkers[i].join();
        }
    }
}
